import JSEncrypt from '@/lib/jsencrypt/jsencrypt.js'

// app外壳的方法 所有和app相关的处理都放在这里面
export default {
	richTextClick(event,vue){
		if(event.detail.node.name=='img'){
			vue.$vm.$cw.previewImg(event.detail.node.attrs.src,vue.$vm.allImgUrls);
		}
	},
	longpressImg(){
		if(this.isApp(false)){
			uni.showActionSheet({
				itemList: ['在微信中打开', '保存到手机'],
				success (res) {
					// 微信打开
					if(res.tapIndex==0){
						
					}else if(res.tapIndex==1){
						
					}
				},
				fail (res) {
					console.log(res.errMsg);
				}
			});	
		}
	},
	// 展示图片
	previewImg(current, urls) {
		urls = urls || current.split(",");
		if(typeof urls=='string'){
			urls=urls.split(",");
		}
		uni.previewImage({
			urls: urls,
			current: current
		});
	},
	// this.$cw.jsEncrypt("{\"id\":\"5a3d6a63-e338-46e5-85e2-08dac6e12f74\",\"className\":\"撒阿松大旦\",\"classGUID\":\"阿松大\",\"studentName\":\"666\",\"studentAge\":\"10\",\"studentBirthday\":\"\",\"studentHeight\":\"\",\"studentIsVip\":\"0\",\"studentLevel\":\"\",\"studentDesc\":\"\",\"studentHeadUrl\":\"\",\"studentMeRemark\":\"\",\"studentFile\":\"\"}");
	jsEncrypt(textOrObj) {
		if(textOrObj){
			if (typeof textOrObj == 'object') {
				textOrObj = JSON.stringify(textOrObj);
			}
			textOrObj = encodeURIComponent(textOrObj);
			let str = getApp().globalData.VuePrototype.$encrypt.encryptLong(textOrObj);
			return str;
			// // 调用Decrypt不能解析那么循环在加密直到可以解析
			// for(let i=0;i<10;i++){
			// 	if(this.jsDecrypt(str)){
			// 		return str;
			// 	}else{
			// 		str = getApp().globalData.VuePrototype.$encrypt.encryptLong(textOrObj);
			// 	}
			// }
			
			// this.showError('加密失败,请刷新后在试');
		}
	},
	// js解密处理
	jsDecrypt(str) {
		if (str) {
			str = decodeURIComponent(str);
			let deStr = decodeURIComponent(getApp().globalData.VuePrototype.$encrypt.decryptLong(str));
			deStr = deStr.replace(/\+/g, ' ');
			if (deStr.includes('}')) {
				return JSON.parse(deStr);
			} else {
				return deStr;
			}
		}
	},
	checkLogin(currentUrl) {
		const notLoginUrls = ['/pages/10home/home','/'];
		const userInfo = getApp().globalData.userInfo;
		if (!userInfo) {
			const url = currentUrl.split('?')[0];
			//判断要打开的页面是否需要验证登录
			if (!notLoginUrls.includes(url)) {
				const loginUrl = `/pages/10home/home?redirect=${encodeURIComponent(currentUrl||'/')}`;
				uni.reLaunch({
					url: loginUrl
				})
				return false;
			}
		}
		return true;
	},

	// 加入拦截校验处理
	addInterceptor() {
		let that = this;
		["navigateTo", "redirectTo", "reLaunch", "switchTab"]
		.forEach(item => {
			//用遍历的方式分别为,uni.navigateTo,uni.redirectTo,uni.reLaunch,uni.switchTab这4个路由方法添加拦截器
			// https://uniapp.dcloud.net.cn/api/interceptor.html#addinterceptor
			uni.addInterceptor(item, {
				invoke(e) { // 调用前拦截
					// getApp().globalData.VuePrototype.$util.baiduEvent('跳转页面',e.url);
					return that.checkLogin(e.url);
				},
				fail(err) { // 失败回调拦截 
					console.log(err);
				}
			})
		})
		// if (!userInfo) {

		// }
		// // #ifdef H5
		// let url = window.location.pathname;
		// if (!notLoginUrls.includes(url)) {
		// 	url =  url + window.location.search;
		// 	const loginUrl = `${window.location.origin}/pages/_common/login/login?redirect=${url}`;
		// 	window.location.href = loginUrl;
		// }
		// // #endif

		// // #ifndef H5
		// const pages = getCurrentPages(); // 获取加载的页面
		// if(pages.length>0){
		// 	const currentPage = pages[pages.length - 1]; // 获取当前页面的对象
		// 	let urlOther = currentPage && `/${currentPage.route}`; // 当前页面url
		// 	if (!notLoginUrls.includes(urlOther)) {
		// 		urlOther = currentPage.$page.fullPath;
		// 		const loginUrl = `/pages/_common/login/login?redirect=${urlOther}`;
		// 		uni.redirectTo({
		// 			url: loginUrl
		// 		});
		// 	}
		// }
		// // #endif
		//}
	},
	// https://uniapp.dcloud.net.cn/univerify.html#
	async setLogin() {
		// 使用时不需要传递 provider
		const univerifyManager = uni.getUniverifyManager();

		// 预登录
		let res = await univerifyManager.preLogin();
		if (res.errMsg == "preLogin:ok") {
			res = await univerifyManager.login({
				univerifyStyle: {
					"fullScreen": true,
					"otherLoginButton": {
						"visible": false, // 是否显示其他登录按钮，默认值：true  
					},
				}
			});
			if (res) {
				res = await uniCloud.callFunction({
					name: 'ulogin', // 你的云函数名称
					data: {
						'access_token': res.authResult.access_token, // 客户端一键登录接口返回的access_token
						'openid': res.authResult.openid // 客户端一键登录接口返回的openid
					}
				})
				if (res) {
					univerifyManager.close();
				}
			}
		}
	},
	// 配置推送处理
	setPush() {
		uni.getPushClientId({
			success: (res) => {
				let push_clientid = res.cid
				console.log('客户端推送标识:', push_clientid)
			},
			fail(err) {
				console.log(err)
			}
		});

		uni.onPushMessage((res) => {
			console.log("收到推送消息：", res) //监听推送消息
		})
	},
	// 注册全局JS方法
	initGlobalMethods(globalData) {
		// 来电变化监听
		window['phoneCallStateChanged'] = async (phone, state, log) => {
		}
	
		// 有事件返回处理
		window['onActivityResult'] = (requestCode, resultCode, data) => {
		}
	
		// 点击totast事件
		window['toastCustomClick'] = () => {
		}
	
		// 点击totast确定
		window['toastSureClick'] = () => {
			if (this.getToastCustomPopType() == 10) {
				this.openInBrower(
					`cwyytapp://pages/homePageSub/orderDetails/orderDetails?bookerPhone=${getApp().globalData.VuePrototype.$globalData.recentCallInObject.phone}`
				);
			} else if (this.getToastCustomPopType() == 20) {
				YYT.OpenRightsSetting();
			}
		}
	
		// anriod弹窗确定
		window['popDialogSureClick'] = (type) => {
			// alert('popDialogSureClick'+type);
		}
	
		// anriod弹窗取消
		window['popDialogCancleClick'] = (type) => {
			//alert('popDialogCancleClick'+type);
		}
	
		// 点击totast取消
		window['toastCancelClick'] = () => {
			this.hideToastCustom();
		}
	
		// 设置位置 精度和维度
		window['setLocation'] = (lg, la) => {
			alert(lg,la);
		}
	
		// 录音的音量
		window['setRecordVoice'] = (voice) => {
	
		}
	
		// 注册安卓按键
		window['phoneKeyDown'] = (keyCode) => {
			// 返回按键
			if (keyCode == 4) {
				// 当不是第一个页面的时候默认返回
				if (YYT.canGoBack(50)) {
					YYT.goBack();
				} else {
					const seconds = getApp().globalData.VuePrototype.$moment().diff(this.AppBackTime, 'seconds');
					if (seconds <= 2) {
						this.exitApp();
					} else {
						uni.showToast({
							title: '再按一次退出程序',
							icon: 'none'
						});
						this.AppBackTime = getApp().globalData.VuePrototype.$moment();
					}
				}
			}
		}
	
		// 注册下载进度事件
		window['showDownProgress'] = (rate) => {
			getApp().globalData.VuePrototype.$u.vuex('vuex_updateProgressNum', rate);
		}
	
		// 切换后台事件
		window['switchFrontBack'] = (value) => {
		}
	
		// webview加载完成调用事件
		window['webViewLoadFinish'] = async () => {
			let res = await this.fileIsExists('app_start_launch.png', 1);
			if (res !== true) {
				this.setLanuchView(true, 0);
			}
		}
	
		// 点击时间事件
		window['timeButtonClick'] = () => {
	
		}
	
		// 设置动画的时间
		this.setLanuchViewTime(3);
		
		if(this.isiOS()){
			this.setLanuchView(true, 0);
		}
	},
	// 获取定位
	/**
	 * var res =await this.$cw.getLocation();
		alert(JSON.stringify(res));
	 */
	getLocation() {
		return new Promise((resolve, reject) => {
			if (this.isApp(false)) {
				if (this.isAndroid()) {
					// 成功返回 “success”
					window['getLocation'] = (oldLongitude, oldLatitude) => {
						const [longitude,latitude]=getApp().globalData.VuePrototype.$util.wgs84togcj02(oldLongitude,oldLatitude);
						var res = {
							longitude,
							latitude
						}
						resolve(res);
					}
					
					YYT.GetLocation();
				} else if (this.isiOS()) {
					// 调用iOS下的insertPhone方法
					window.webkit.messageHandlers.iOS.postMessage({
						method: 'getLocation'
					})
					// 成功返回 “success”
					window['getLocation'] = (oldLongitude, oldLatitude) => {
						const [longitude,latitude]=getApp().globalData.VuePrototype.$util.wgs84togcj02(oldLongitude,oldLatitude);
						var res = {
							longitude,
							latitude
						}
						resolve(res);
					}
				}
			}
		});
	
		if (this.isApp(false)) {
			if (this.isAndroid()) {
				return JSON.parse(YYT.GetLocation());
			} else if (this.isiOS()) {
				window.webkit.messageHandlers.iOS.postMessage({
					method: 'getLocation'
				});
			}
		}
	},
	// 退出app
	exitApp() {
		if (this.isApp(false)) {
			if (this.isAndroid()) {
				YYT.ExitApp();
			} else if (this.isiOS()) {
				window.webkit.messageHandlers.iOS.postMessage({
					method: 'exitApp',
					params: {
						payStr: ''
					}
				});
			}
		}
	},
	// 是否为首页
	isFirstPage() {
		//获取微信的所有页面
		const currentPages = getCurrentPages();
		const pageLen = currentPages.length;
		//判断是否是第一个页面，如果是有设置back为true的页面，将不显示返回箭头，而现实返回首页按钮
		if (pageLen == 1) {
			return true;
		}
	
		return false;
	},
	isiOS() {
		return typeof iOS != 'undefined'
	},
	isAndroid() {
		return typeof YYT != 'undefined'
	},
	// 判断是否是app
	isApp(isShow=false) {
		if (this.isAndroid()) {
			return true
		} else if (this.isiOS()) {
			return true
		} else {
			if (isShow) {
				uni.showToast({
					title: '该功能需在APP上使用',
					duration: 2000,
					icon: 'none',
				})
			}
			return false
		}
	},
	/** 设置手机的缓存
	 * var s={
			name:'123'
		}
		var res= await this.$cw.setPhoneCache('test',JSON.stringify(s));
	 * @param {Object} key
	 * @param {Object} value
	 */
	setPhoneCache(key, value) {
		return new Promise((resolve, reject) => {
			if (this.isApp(false)) {
				if (this.isAndroid()) {
					const res = YYT.setPhoneCache(key, value);
					resolve(res);
				} else if (this.isiOS()) {
					// 调用iOS下的insertPhone方法
					window.webkit.messageHandlers.iOS.postMessage({
						method: 'setPhoneCache',
						params: {
							key,
							value
						},
					})
					// 成功返回 “true”
					window['setPhoneCache'] = (res) => {
						resolve(res);
					}
				}
			}
		});
	},
	/**是否存在文件
	 * await this.$cw.fileIsExists('app_start_launch.png');
	 * @param {*} filePath 文件路径
	 * @param {*} saveType 保存方式 0保存为外部文件 1保存为内部文件
	 */
	fileIsExists(filePath, saveType = 0) {
		return new Promise((resolve, reject) => {
			if (this.isApp(false)) {
				if (this.isAndroid()) {
					const res = YYT.FileIsExists(filePath, saveType);
					resolve(res);
				} else if (this.isiOS()) {
					// 调用iOS下的insertPhone方法
					window.webkit.messageHandlers.iOS.postMessage({
						method: 'fileIsExists',
						params: {
							filePath
						},
					})
					// 成功返回 “true”
					window['fileIsExists'] = (res) => {
						resolve(res);
					}
				}
			}
		});
	},
	async setLanuchViewTime(time) {
		let res = await this.setPhoneCache('lanuchViewTime', time);
		return res;
	},
	
	// 设置this.$cw.setLanuchView(false,3);
	setLanuchView(isHidden, lanuchTime = 5) {
		return new Promise((resolve, reject) => {
			if (this.isApp(false)) {
				if (this.isAndroid()) {
					YYT.setLanuchView(isHidden, lanuchTime);
				} else if (this.isiOS()) {
					window.webkit.messageHandlers.iOS.postMessage({
						method: 'setLanuchView',
						params: {
							isHidden,
							lanuchTime
						},
					})
				}
			}
		});
	},
}